#!/usr/bin/env python
# coding:utf-8

# -*- coding: utf-8 -*-
# @Time   :18-9-12 下午4:02
# @Author : xuyanbin
# @Email  : xuyanbin-x@163.com

import requests
import sys
import logging
import os
import json


def sent_wechat_alarm(alarm_type,problem,msg):
    '''
    因为大多服务器都预装python2，故该脚本使用python。日志文件位置：/tmp/weixin.log
    :param host: 告警主机
    :param level: 级别
    :param msg: 消息内容
    :return:
    '''
#    logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s, %(filename)s, %(levelname)s, %(message)s',
#                    datefmt = '%a, %d %b %Y %H:%M:%S',
#                    # filename = os.path.join('/usr/lib/zabbix/alertscripts','weixin.log'),
#                    filename = os.path.join('/tmp/','weixin.log'),
#                    filemode = 'a')
    #corpid  appsecret  agentid  三个值在企业微信中查找
    corpid='wwaa34d45d5f0e0570'
    appsecret='f_SnACSO5FlsilBCWLAU2L9pJFC5zkoSw5cBmSKjeZY'
    agentid=1000003

    #获取accesstoken
    token_url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + appsecret
    req=requests.get(token_url)
    accesstoken=req.json()['access_token']   #获取accesstoken，访问应用时要带着accesstoken,和agentid

    #获取应用,发生高级人id
    url = 'https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token=%s&agentid=%s'%(accesstoken,agentid)
    app_req=requests.get(url)
    # print app_req.text
    # print url

    data = json.loads(app_req.text) #将json转为字典
    userid_li = data.get('allow_userinfos').get('user')  #获取成员
    # for i,k in enumerate(userid_li):
    #     pass
    #有多个告警人，在这里写多个
    user1 = userid_li[0].get('userid')
    user2 = userid_li[1].get('userid')
    user3 = userid_li[2].get('userid')
    user4 = userid_li[3].get('userid')
    user5 = userid_li[4].get('userid')

    # print user1
    # send_to='%s|%s'%(user1,user2)
    send_to='%s|%s|%s|%s|%s'%(user1,user2,user3,user4,user5)
    print send_to

#    logging.info('开始发生告警')
#    logging.info('sendto:' + send_to + ';;host:' + host + ';;message:' + msg)

    #发送消息
    msgsend_url='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken

    # 调用脚本时带一个参数为告警类型，在zabbix的用户中定义,第二个参数是问题描述，第三个参数是msg
    # alarm_type = sys.argv[1]
    # problem = sys.argv[2]
    # msg = sys.argv[3]
    params={
            "touser":  send_to,  #成员ID多个的时候以|隔开
          # "toparty": toparty,    #部门id
            "msgtype": "text",     #消息类型，发生文本是固定为text
            "agentid": agentid,    #应用id
            "text": {              #消息内容，不超过2048个字节
                    "content": '告警类型： '+alarm_type+'\n'+problem+'\n'+'内容: '+msg
            },
            "safe":0
    }
    #发送告警信息
    send_req=requests.post(msgsend_url, data=json.dumps(params))
    print send_req.text
    print send_req.status_code

#    logging.info('消息发生完成')

sent_wechat_alarm(sys.argv[1],sys.argv[2],sys.argv[3])
